package com.ys.controller.api.hr;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.ys.service.flow.YspTaskService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ys.config.MenuId;
import com.ys.entity.hr.ThrVatApply;
import com.ys.entity.hr.ThrVatApplyDetail;
import com.ys.entity.sys.YsCol;
import com.ys.enume.finance.PaymentEnum;
import com.ys.enume.flow.FlowEnum;
import com.ys.enume.sys.YsColEnum;
import com.ys.service.hr.ThrVatApplyService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService.UploadDto;
import com.ys.util.ExportExcelUtils;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

@Controller
@RequestMapping("/api/inter/thrVatApply")
public class ApiInterThrVatApplyController {
	
//	private static final Logger logger = Logger.getLogger(ApiAdminLoginController.class);
	
	@Autowired
	private CommonApiService<ThrVatApply> commonApiService;
	@Autowired
	private CommonApiService<ThrVatApplyDetail> commonApiServiceDetail;
	@Autowired
	private ThrVatApplyService thrVatApplyService;

	@Autowired
	private YspTaskService yspTaskService;

	
	@RequiresPermissions("thrVatApply:view")
	@RequestMapping("/search")
    @ResponseBody
	public LayuiTableVoJA search(@ModelAttribute ThrVatApplyDetail cond){
		
		cond = setSeachSql(cond);
		return commonApiServiceDetail.searchLay(cond);
	}
	
	@RequestMapping("/searchForModal")
    @ResponseBody
	public LayuiTableVoJA searchForModal(@ModelAttribute ThrVatApplyDetail cond){

		cond.setStatePay(PaymentEnum.StatePay.INIT.value);
    	
    	cond.addLeftJoin("THR_VatApply B ON B.Bid = A.Pbid")
    		.addField("B.Bid bid")
    		.addField("B.EffectStock effectStock")
    		.where("B.EffectStock = " + FlowEnum.EffectStock.EFFECTED.value);
    	
    	cond.addLeftJoin("THR_OperateCompanyEuropeTrade B1 on B1.VatNo = A.VatNo")
    		.addLeftJoin("THR_OperateCompanyApply B2 on B2.Vgsbm = B1.Vgsbm")
			.addField("B2.Vgsbm vgsbm")
    		.addField("B2.Vgsjc vgsjc");
    	
    	cond.addLeftJoin("TCW_VatPaymentAccount C ON C.Code = A.VatPaymentAccountCode")
			.addField("C.Vyhzhmc vyhzhmc")
			.addField("C.Vyhzh vyhzh")
			.addField("C.AchRouting vaba")
			.addField("C.Vkhh vkhh")
			.addField("C.SwiftCode swiftCode");
    	
    	cond.addField("A.TaxAmount billingAmount")
    		.addField("A.VatNo vbzCode")
    		.addField("A.Remark vbz");
    	
		return commonApiServiceDetail.searchLay(cond);
	}
	
	/**
	 * 获取上个申报周期
	 */
	@RequestMapping("/getLastApply")
	@ResponseBody
	public R getLastApply(String vatNo) {
		
		if (vatNo == null || vatNo.length() == 0) {
			return R.error("VAT号为空");
		}
		
		Map<String, String> dataMap = new HashMap<String, String>();
		ThrVatApplyDetail lastDetail = new ThrVatApplyDetail().setVatNo(vatNo)
				.setOrderby("A.Id DESC")
				.queryFirst();
		if (lastDetail != null) {
			dataMap.put("lastDateBegin", lastDetail.getCurrentDateBegin());
			dataMap.put("lastDateEnd", lastDetail.getCurrentDateEnd());
			return R.ok(dataMap);
		} else {
			return R.error("没有最新申报");
		}
	}
	
	/**
	 * 新增
	 */
	@RequestMapping("/add")
	@ResponseBody
	@RequiresPermissions("thrVatApply:add")
	public R add(String bid, String subData) {
		try {
			//修改
			return thrVatApplyService.add(bid, subData, MenuId.THR_VatApply);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}

	/**
	 * 编辑
	 */
	@RequiresPermissions("thrVatApply:add")
	@PostMapping("/edit")
    @ResponseBody
	public R edit(String bid, String subData){
		try {
			return thrVatApplyService.edit(bid, subData, MenuId.THR_VatApply);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}
	
	/**
	 * 流转通过
	 */
	@RequiresPermissions("thrVatApply:add")
	@PostMapping("/flowPass")
    @ResponseBody
	public R flowPass(HttpServletRequest request, Long id){
		ThrVatApply thrVatApply = new ThrVatApply().setId(id).queryFirst();
		try {
			return thrVatApplyService.flowPass(thrVatApply.getBid(), ShiroUtils.getUserId());
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}
	
	/**
	 * 流转驳回
	 */
	@RequiresPermissions("thrVatApply:add")
	@PostMapping("/flowRefuse")
    @ResponseBody
	public R flowRefuse(HttpServletRequest request, Long id, String reason){
		ThrVatApply thrVatApply = new ThrVatApply().setId(id).queryFirst();
		try {
			return thrVatApplyService.flowRefuse(thrVatApply.getBid(), reason, ShiroUtils.getUserId());
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}



	/**
	 * 流转驳回
	 */
	@RequiresPermissions("thrVatApply:add")
	@PostMapping("/flowInit")
	@ResponseBody
	public R flowInit(HttpServletRequest request, Long id, String reason){
		ThrVatApply thrVatApply = new ThrVatApply().setId(id).queryFirst();
		try {
			return yspTaskService.flowInit(thrVatApply.getBid(), reason, ShiroUtils.getUserId());
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}
	
	/**
	 * 删除
	 */
	@PostMapping("/delete")
    @ResponseBody
	public R delete(Long id){
		
		try {
			return thrVatApplyService.deleteTrue(id);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("操作失败，请联系客服");
		}
	}
	
	/**
	 * 取消
	 */
	@RequiresPermissions("thrVatApply:cancel")
	@PostMapping("/cancel")
    @ResponseBody
	public R cancel(String bid){

		return thrVatApplyService.cancel(bid);
	}
	
	/*
	 * 导出
	 */
	@RequiresPermissions("thrVatApply:export")
	@RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute ThrVatApplyDetail cond) throws Exception{
		
		cond = setSeachSql(cond);
		cond.setOrderby("A.Id DESC");
		
		cond.setPage(0).setSize(999999);

		List<Map<String, Object>> listData = cond.queryMap();
        
    	List<YsCol> listField = new YsCol()
    			.setMenuId(MenuId.THR_VatApply)
    			.setFrontShow(YsColEnum.FrontShow.SHOW.value)
    			.setOrderby("A.SortNo asc")
    			.queryList();
    	
    	
        ExportExcelUtils<ThrVatApply> util = new ExportExcelUtils<ThrVatApply>(new ThrVatApply());
        
        String toFilePath = util.exportExcel(listData, listField, "VAT申报单");
        UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
        return R.ok(dto.getUrl());
    }

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public ThrVatApplyDetail setSeachSql(ThrVatApplyDetail cond){
    	
    	cond.addLeftJoin("THR_VatApply B ON B.Bid = A.Pbid")
    		.addField("B.Bid bid")
    		.addField("B.EffectStock effectStock");
    	
    	cond.addLeftJoin("THR_OperateCompanyEuropeTrade B1 on B1.VatNo = A.VatNo")
    		.addLeftJoin("THR_OperateCompanyApply B2 on B2.Vgsbm = B1.Vgsbm")
			.addField("B2.Vgsbm vgsbm")
    		.addField("B2.Vgsjc vgsjc")
    		.addLeftJoin("TB_Country B3 on B3.Code = B1.CountryCode")
			.addField("B3.Code countryCode")
    		.addField("B3.Name countryName")
    		.addLeftJoin("TS_UserChange B4 on B4.Id = B2.OperatorChangeId")
			.addField("B4.UserId operatorUserId")
			.addField("B4.UserName operatorUserName");
    	
    	cond.addLeftJoin("YS_ProcInst C ON C.Bid = B.Bid")
    		.addField("C.UpdateTime auditTime");
    	
    	cond.addLeftJoin("TS_UserInfo D ON D.UserId = C.CreateUserId")
    		.addField("D.UserId createUserId")
    		.addField("D.UserName createUserName");
    	cond = commonApiServiceDetail.dataAuth(MenuId.THR_VatApply, cond);
		
        return  cond;
    }
}
